/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */
"use strict";
const extend = require('extend');
const router = require('express').Router();
const _route = {
    index: require('./viewRoutes/index'),

    _renderParam: function (url, req) {
        return {
            path: url,
            queryData: req.query || {},
            session: req.session || {},
            userData: req.session.userData || {},
            cookie: req.cookies || {},
            data: {},
            redirect: req.url,
            title: global.config.title
        };
    },

    _parseOpenId: function (openId, req, res, next) {
        let me = this;
        if (openId) {   //如果可以获取到openId的话，则获取用户信息
            req.session.openId = openId;
            global.tool.getUserInfo(openId, function (uData) {
                console.log("============databaseUser==============");
                console.log(uData);
                console.log("============databaseUser==============");
                global.weChatUtil.getUserInfo(openId, function (weData) {
                    console.log("============wechatUser==============");
                    console.log(weData);
                    console.log("============wechatUser==============");
                    let userData = uData;
                    //从缓存中取barCode
                    extend(true, userData, weData);
                    req.session.userData = userData;
                    let language = req.session.userData.language || "en";
                    req.setLocale(language.substr(0, 2));
                    me._render(req, res, next);
                });
            });
        } else {
            res.send('<!DOCTYPE HTML><html><head><meta charset="UTF-8">' +
                '<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">' +
                '<meta http-equiv="X-UA-Compatible" content="IE=Edge">' +
                '<meta name="apple-mobile-web-app-capable" content="yes" />' +
                '<meta name="apple-mobile-web-app-status-bar-style" content="black" /></head>' +
                '<body ontouchstart>刷新成功，请关闭当前页面，重新打开！谢谢！</body></html>');
        }
    },

    _render: function (req, res, next) {
        let url = req.session.endType + (req.path.endsWith('/') ? req.path + "index" : req.path)
            , routes = req.path.split("/")
            , skip = true
            , renderParam = this._renderParam(url, req);
        if (routes.length > 1) { //目前我们支持二层的url结构
            console.log('~~~~~~~~~~~~~~~~~~~~~~~~routes start~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
            console.log(routes);
            console.log('~~~~~~~~~~~~~~~~~~~~~~~~routes end~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
            try {
                let fun;
                if (routes.length == 2)
                    fun = _route['index'][routes[1]];
                else if (routes.length = 3)
                    fun = _route[routes[1]][routes[2]];
                if (fun != null) {
                    console.log('~~~~~~~~~~~~~~~~~~~req.session.userData info start~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
                    console.log(req.session.userData);
                    console.log('~~~~~~~~~~~~~~~~~~~req.session.userData info end~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
                    skip = false;
                    fun(req, res, function (data, permission, response) {
                        console.log('~~~~~~~~~~~~~~~~permission info start~~~~~~~~~~~~~~~~~~~~~~~~~~');
                        console.log(permission);
                        console.log('~~~~~~~~~~~~~~~~permission info end~~~~~~~~~~~~~~~~~~~~~~~~~~');

                        if(req.session.userData.id == undefined){//游客
                            if(
                                (routes[0] == '' && routes[1] == 'index') //我要租房
                                || (routes[0] == '' && routes[1] == 'news') //科寓动态
                                || (routes[0] == '' && routes[1] == 'houseInfo') //首页推荐房源
                                || (routes[0] == '' && routes[1] == 'shortRentList') //我要短租
                                || (routes[0] == '' && routes[1] == 'houseSearch') //我要长租
                                || (routes[0] == '' && routes[1] == 'shortRentDetail') //点击我要短租列表
                                || (routes[0] == '' && routes[1] == 'bindAccount') //去认证
                            ){
                               /**
                                * 客户后来提出需求允许未注册用户可以查看某些页面
                                * 所以临时用这种比较low的方法解决，后面有时间再修改
                                */
                            }else{
                                url = 'mobile/noAccess';
                            }
                        }else{//会员
                            if (permission && permission > req.session.userData.status) {
                                url = 'mobile/noAccess';
                            }
                        }
                        if (response && response.statusCode && response.statusCode != 200) {
                            let err = new Error('内部错误');
                            err.status = response.statusCode;
                            next(err);
                        } else {
                            renderParam.data = data;
                            res.render(url, renderParam);
                        }
                    }, next);
                }
            } catch (e) {
            }
        }
        if (skip) {
            res.render(url, renderParam);
        }
    }
};

// 该路由使用的中间件
router.use(function timeLog(req, res, next) {
    console.log('view::' + req.path, Date.now());
    next();
});

router.get('/logout', function (req, res, next) {
    delete req.session.userData;
    res.redirect(global.config.contextPath + global.config.viewPrefix + '/');
});

/**
 * 实现路由转发
 */
router.use('/', function (req, res, next) {
    let userInfo = req.session.openId;
    // req.session.endType = global.tool.endType(req.headers['user-agent']);
    // if (req.session.endType != 'mobile') {
    //     res.json("只支持手机端访问");
    //     return;
    // }
    req.session.endType = "mobile";
    if (!userInfo) {
        if (global.config.production) {
            if (req.query.code) {
                global.weChatUtil.getOpenId(req.query.code, function (openId) {
                    _route._parseOpenId(openId, req, res, next);
                });
            } else {
                _route._parseOpenId(req.query.openId, req, res, next);
            }
        } else {
            res.render(req.session.endType + '/login', _route._renderParam('login', req));
        }
    } else {
        let language = req.session.userData.language || "en";
        req.setLocale(language.substr(0, 2));
        _route._render(req, res, next);
    }
});

module.exports = router;
